<template>
    <el-drawer ref="drawRef" class="reset" v-model="dialogVisible" :title="'上传资料'" :destroy-on-close="true"
        :before-close="handleClose" :size="isMobile ? '100%' : 570" :close-on-press-escape="false" :close-on-click-modal="false">
        <!-- <div class="flex flex-jc-sb border-bottom pd-b-10 mg-b-20">
            <div class="fs-16 bold"></div>
        </div> -->
        <div class="w-full box-border p-16px">
            <el-form ref="formRef" :model="formData" :rules="rules" label-position="top" class="">
                <div class="grid">
                    <el-form-item v-for="(i, index) in formData" :key="index" :label="i.label" :prop="`${i.prop}.value`">
                        <template #label>
                            <div class="header mg-b-20 fs-14 flex items-center fc-main">
                                <span>
                                    {{ i.name }}（{{ i.valueUrl.length }}/{{ i.limitSize }}）
                                </span>
                                <span v-if="i.required" class="fc-red mg-l-5 mg-r-5">*</span>
                                <span class="hint fs-14 fc-lightgrey">{{ i.detail }}</span>
                            </div>
                        </template>
                        <div class="reset-card">
                            <uploadImage can-compress :file-url="i.valueUrl"
                                prop-name="fileUrl" :limit="i.limitSize" :limit-size="10" remove-confirm :preview-list="previewList"
                                @success="handleSuccess($event, i)" @remove="handleRemove($event, i)">
                                <template #button>
                                    <div class="flex items-center">
                                        <el-icon>
                                            <Upload class="fc-primary fs-14" />
                                        </el-icon>
                                        <span class="fc-primary">上传附件</span>
                                        <span class="fs-14 fc-hintgrey mg-l-20">大小限制10MB，支持png，jpeg，jpg</span>
                                    </div>
                                </template>
                            </uploadImage>
                        </div>
                    </el-form-item>
                </div>
            </el-form>
        </div>
      <template #footer>
        <div class="flex flex-jc-c">
          <el-button type="primary" plain @click="doExport">导出</el-button>
        </div>
      </template>
    </el-drawer>
</template>
<script setup>
import { ref, computed, watch } from 'vue'
import { cloneDeep } from 'lodash'
import uploadImage from '@/components/uploadImage/index.vue'
import { exportImagesLong, getMaterialsLong, addMaterialsLong, removeMaterialsLong, exportImagesDay, getMaterialsDay, addMaterialsDay, removeMaterialsDay } from '@/api/clients/index.ts'
import { useStore } from '@/store/index.ts'
const store = useStore()
const isMobile = ref(window.isMobile)

const drawRef = ref(null)

const formRef = ref(null)

const previewList = ref([])

const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    curItem: {
        type: Object
    },
    insureType: {
        type: String
    }
})

const emits = defineEmits(['update:show', 'success'])

const dialogVisible = ref(false)

const axios = {
    long: {
        getMaterial: getMaterialsLong,
        addMaterial: addMaterialsLong,
        removeMaterial: removeMaterialsLong,
        export: exportImagesLong
    },
    day: {
        getMaterial: getMaterialsDay,
        addMaterial: addMaterialsDay,
        removeMaterial: removeMaterialsDay,
        export: exportImagesDay
    }
}


const formData = ref({})

const rules = ref({
    'basicInfo.yearMonth.value': [
        {
            required: true,
            trigger: 'change',
            message: '生效年月不能为空'
        }
    ],
})

const getData = () => {
    formData.value = {}
    axios[props.insureType].getMaterial({
        reportCaseId: props.curItem.id,
        insureCompany: props.curItem.insurCompany || props.curItem.insureCompanyType
    }).then(res => {
        res.forEach(i => {
            formData.value[i.type] = {
                ...i,
                valueUrl: i.files,
                required: !!i.isRequired
            }
            // formData.value[i.type].valueUrl = i.files
            // formData.value[i.type].limit = i.limitSize
            // formData.value[i.type].name = i.name
            // formData.value[i.type].hint = i.detail
            // formData.value[i.type].required = !!i.isRequired
        })

        const list = res.map(i => i.files).flat()

        previewList.value = list.map(i => i.fileUrl)
        console.log(333, formData.value)
    })
}

const submit = () => {
    for (const key in formData.value) {
        if (formData.value[key].required && !formData.value[key].value?.length) {
            ElMessage.error({
                message: `${formData.value[key].name}不能为空`
            })
            return
        }
    }
}

const doExport = () => {
    axios[props.insureType].export({
        reportCaseId: props.curItem.id,
        insureCompany: props.curItem.insurCompany || props.curItem.insureCompanyType
    }).then((blob) => {
        const blobs = new Blob([blob], {
            type: 'application/zip'
        })
        const a = document.createElement('a')
        const URL = window.URL || winodw.webketURL
        a.href = URL.createObjectURL(blobs)
        a.download = store.fileName
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        ElMessage.success({
            message: '文件下载中，请稍作等待'
        })
    })
}

const handleClose = (done) => {
    const values = Object.values(formData.value)
    const requireList = values.filter(i => i.required)
    done()
    // if (requireList.some(i => !i.valueUrl?.length)) {
    //     ElMessageBox.confirm(
    //         '您还有必填的资料未上传，是否确认退出？',
    //         '提示',
    //         {
    //             confirmButtonText: '确定',
    //             cancelButtonText: '取消',
    //             type: 'warning',
    //         }
    //     )
    //         .then(() => {
    //             done()
    //         })
    //         .catch(() => {
    //         })
    // } else {
    //     done()
    // }
}

const handleSuccess = (base64, i) => {
    axios[props.insureType].addMaterial({
        reportCaseId: props.curItem.id,
        categoryType: i.type,
        file: base64,
        companyId: props.curItem.companyId
    }).then(res => {
        i.valueUrl.push({
            fileId: res.fileId,
            fileUrl: res.fileUrl
        })
        getData()
        // console.log(555, i);
    })
}

const handleRemove = (file, i) => {
    axios[props.insureType].removeMaterial(file.fileId).then(res => {
        const index = i.valueUrl.findIndex(k => k.fileId === file.fileId)
        if (index!==-1) {
            i.valueUrl.splice(index, 1)
        }
        ElMessage.success({
            message: '删除成功'
        })
    })
}

watch(() => props.curItem, (newval) => {
    // console.log(212121, newval);
    if (!newval) return
    // if (props.insureType === 'day') {
    //     // 日日保
    //     formData.value = cloneDeep(dayInsurance)
    // } else {
    //     // 长期保
    //     switch (newval.insurCompany) {
    //         // 阳光保险
    //         case 'insure002_gsc':
    //         case 'period_003_yg':
    //             formData.value = cloneDeep(sunnyInsurance)
    //             break
    //         // 现代财
    //         case 'period_002_xdc':
    //             formData.value = cloneDeep(nowInsurance)
    //             break
    //     }
    // }

}, {
    immediate: true,
    deep: true
})

watch(() => props.show, (newval) => {
    dialogVisible.value = newval
    if (newval) {
        getData()
    }
})

watch(dialogVisible, (newval) => {
    emits('update:show', newval)
    if (!newval) {
        // formRef.value.resetFields()
    }
})
</script>
<style lang="scss" scoped>
.header {
    &::before {
        content: '';
        border-left: 4px solid #0256FF;
        height: 14px;
        margin-right: 5px;
    }
}

.grid {
    // display: grid;
    // grid-template-columns: repeat(2, 1fr);
    // gap: 0 30px;
}

:deep(.reset .el-input__wrapper) {
    display: flex;
}

:deep(.reset-card .el-upload--picture-card) {
    justify-content: start;
    background: #fff;
}

:deep(.reset-card .el-upload-list__item) {
    width: 72px;
    height: 72px;
}

:deep(.reset .el-drawer__header) {
    margin-bottom: 0;
}
</style>
